package algoritmoHiru;



import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Enumeration;

public class TaskC extends Thread {
	 public void run (){
		 
			try {
				int mezuTamaina=1024;//jakin beharko da zein den mezuak har dezaken tamaina maximoa;
				byte [] buffer = new byte[mezuTamaina];
				DatagramSocket socketa= new DatagramSocket(7777);
				DatagramPacket paketea= new DatagramPacket(buffer,buffer.length);
				while(true){
				socketa.receive(paketea);
				if (Hasieraketa.leader==null){
					Hasieraketa.prozesuKont++;//leaderraren bila ari gara eta prozesu batek bidali digu bere erantzuna
					for(Enumeration <Makina> e=MakinaBektorea.getInstance().hash.elements();e.hasMoreElements();){
						ByteArrayInputStream bos = new ByteArrayInputStream(buffer);
					    ObjectInputStream oos = new ObjectInputStream(bos);
					    int[]jasotakoRecovered=(int[]) oos.readObject();
					    String leader=(String) oos.readObject();
					    oos.close();
					    bos.close();
					    /**************************PROBAK*************************/
					    System.out.println("honakoa jaso da");
					    for(int x=0 ;x<jasotakoRecovered.length;x++  ){
					    	System.out.println(jasotakoRecovered[x]);
					    }
					    /**************************AMAIERA PROBAK*************************/
						
						for (int i=0;i<Hasieraketa.recovered.length;i++){
							Hasieraketa.recovered[i]=Math.max(Hasieraketa.recovered[i], jasotakoRecovered[i]);		
						}
						String bidaltzailea=paketea.getAddress().getHostName();//mejora bezela makinak konparatzeko orduan IP erabiliko dugu.
						System.out.println("pakete bidaltzailea: "+bidaltzailea);
						Hasieraketa.candidates.put(bidaltzailea,0);
						Hasieraketa.candidates.put(leader, 0);
						
						//if p has received PONG from [n/2] processes
						if (Hasieraketa.prozesuKont>=MakinaBektorea.getInstance().hash.size()/2){
						
							//for all Candidates.....
							//timeout<-max(timeout, recovered)
						Hasieraketa.update_leader();
						for (Enumeration <String> unekoMakina=Hasieraketa.candidates.keys();unekoMakina.hasMoreElements();){
							MakinaBektorea.getInstance().hash.get(unekoMakina).timeout=Math.max(MakinaBektorea.getInstance().hash.get(unekoMakina).timeout, Hasieraketa.recovered[MakinaBektorea.getInstance().hash.get(unekoMakina).pos]);
							Hasieraketa.timer=MakinaBektorea.getInstance().hash.get(bidaltzailea).timeout;//
						}
						//reset timeout KONTUZ!!!!!!!!! behitu algoritmoaBin zeatik eztaon agindu hau jarrita
						
						
						}
					}
				}
				}
			}catch(Exception ex){}
	 }
}
